$:.unshift File.join(File.dirname(__FILE__), "..", "lib")
$KCODE = 'utf-8'

require 'UPnP/service/content_directory'
require 'builder'
require 'test/unit'
require 'rexml/document'
include REXML

#mock class to provide MySQL channel data 
class UPnP::Service::MythContainer
  def each_channel(sql_query)
    #chanid, channum, name, icon, starttime, endtime, title, subtitle, description, category
    [%w[1024 24 Bell\ ExpressVu\ Info\ Channel /home/yuchem/.mythtv/channels/bell_expressvu.jpg 10:00 12:00 Test\ title],
     %w[1033 33 Bell\ ExpressVu\ HD\ promo /home/yuchem/.mythtv/channels/bell_expressvu.jpg]
    ].each {|row| yield row}
  end
end

class TestMythContentDirectory < Test::Unit::TestCase
  class FakeWEBrickSocket
  
      #Method that emulates Socket addr return
      def addr
        #_, port, host, addr = 
    
        return nil, 80, 'localhost', '127.0.0.1'
      end
  end
  
  class DeviceMockup
    #Emulating Device#parent method
     def parent
       nil
     end
     
     def type
       'MediaServer'
     end    
  end

  @@cd = UPnP::Service::ContentDirectory.new DeviceMockup.new, 'ContentDirectory' do |cd|
    #trick to emulate WEBrick Socket presence, its .addr method is called later
    cd.add_mythtv '/home/yuchem/.mythtv/channels', 'localhost', 'mythconverg', 'mythtv', 'manatee'
                 
  end

  def setup
    Thread.current[:WEBrickSocket] = FakeWEBrickSocket.new
 
  end 
 
  def test_browse_structure
    # MythTV
    # Favorites
    #   ...
    # All Channels
    #   1024 
    #   1033 ...
    
    #structure under MythTV
    _, result, number_returned, total_matches, update_id = @@cd.Browse(1, 'BrowseDirectChildren', '*', 0,  0, nil)
    
    dir = []
    xml = Document.new(result)
    xml.each_element('//dc:title') {|e| dir << e.text}
      
    assert_equal('All Channels,Favorites', dir.join(','), 'Folders under Myth')
    assert_equal(2, number_returned, 'Returned objects under Myth')
    assert_equal(2, total_matches, 'Total objects under Myth')
        
    #for the following testing
    f_id = xml.elements["//container[dc:title='Favorites']"].attributes['id']
    a_id = xml.elements["//container[dc:title='All Channels']"].attributes['id']

    #structure under All Channels
    _, result, number_returned, total_matches, update_id = @@cd.Browse(a_id, 'BrowseDirectChildren', '*', 0,  0, nil)

    dir = []
    xml = Document.new(result)
    xml.each_element('//upnp:channelNr') {|e| dir << e.text}
      
    assert_equal('1024,1033', dir.join(','), 'Channels under All')
    assert_equal(2, number_returned, 'Returned objects under Myth')
    assert_equal(2, total_matches, 'Total objects under Myth')

    i = xml.elements["//item[upnp:channelNr='1024']"] 
    
    assert_nil(i.attributes['childCount'])
    assert_equal(a_id, i.attributes['parentId'], 'All Channels is a parent of this item')
    assert_equal('object.item.videoItem.videoBroadcast', i.elements['upnp:class'].text)
    assert_match(%r[^http://\d[\d:\.]+/MediaServer/ContentDirectory/1/.+], i.elements['upnp:icon'].text)
    assert_match(%r[^http-get:\*:video/\w+:\*], i.elements['res'].attributes['protocolInfo'])
    assert_match(%r[^http://\d[\d:\.]+/MediaServer/ContentDirectory/#{UPnP::Service::MythContainer::ServletName}/\d+], i.elements['res'].text)
    assert_nil(i.elements['res'].attributes['size'], 'Size must attribute must not be present')

  end
end